//
//  YCDownloadDataManager.m
//  YCSchool
//
//  Created by Yanglixia on 16/5/15.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//

#import "YCDownloadDataManager.h"

NSString * const YCDownloadDataManagerDefaultCachePath = @"com.YCSchool.download";

@implementation YCDownloadDataManager


+ (instancetype)sharedManager
{
    static YCDownloadDataManager *shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        //NSString *md5Path = [[GOLoginUser loginUser].userId go_md5String];
        NSString *docPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
        NSString *cachePath = [docPath stringByAppendingPathComponent:YCDownloadDataManagerDefaultCachePath];
        //cachePath = [cachePath stringByAppendingPathComponent:md5Path];
        shared = [[self alloc] initWithCachePath:cachePath];
    });
    return shared;
}

- (instancetype)initWithCachePath:(NSString *)cachePath
{
    if(self = [super init])
    {
        _cachePath = cachePath;
    }
    return self;
}

- (BOOL)downloadDataWithURL:(NSURL *)url completionHandlerCallBack:(YCDownloadCompletionHandlerCallBack)completionHandlerCallBack
{
    NSString *filename = [[url absoluteString] yc_md5String];
    NSString *filepath = [[self.cachePath stringByAppendingPathComponent:filename] stringByAppendingPathExtension:url.pathExtension];
    NSFileManager *manager = [NSFileManager defaultManager];
    if([manager fileExistsAtPath:filepath])
    {
        completionHandlerCallBack(nil,[NSURL fileURLWithPath:filepath],YCDownloadDataManagerDataFromCache,nil);//下载从缓存中找到的
    }
    else
    {
        if(![manager fileExistsAtPath:self.cachePath])
        {
            [manager createDirectoryAtPath:self.cachePath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
        
        NSURLSessionDownloadTask *downloadTask = [[AFHTTPSessionManager manager] downloadTaskWithRequest:urlRequest progress:nil destination:^NSURL * (NSURL *  targetPath, NSURLResponse * response) {
            return [NSURL fileURLWithPath:self.cachePath];//返回要存放的地址
        } completionHandler:^(NSURLResponse * response, NSURL * filePath, NSError * error) {
            if (error) {//下载失败,移除文件
               [[NSFileManager defaultManager] removeItemAtPath:filepath error:nil];
                completionHandlerCallBack(nil,nil,YCDownloadDataManagerDataFromInternet,error);
            } else {
                completionHandlerCallBack(response,filePath,YCDownloadDataManagerDataFromInternet,nil);
            }
        }];
        [downloadTask resume];
    }
    
    return YES;
}

- (BOOL)cacheExitsForURL:(NSURL *)url
{
    NSString *filename = [[url absoluteString] yc_md5String];
    NSString *filepath = [[self.cachePath stringByAppendingPathComponent:filename] stringByAppendingPathExtension:url.pathExtension];
    NSFileManager *manager = [NSFileManager defaultManager];
    return [manager fileExistsAtPath:filepath];
}



@end
